package com.currency.mall.ui.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.adapter.SearchAdapter;
import com.currency.mall.adapter.SearchHistoryAdapter;
import com.currency.mall.entity.CollectShareId;
import com.currency.mall.entity.SharesBean;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.login.LoginActivity;
import com.currency.mall.ui.main.inquiry.InquiryDetailsActicity;
import com.currency.mall.util.Util;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbusines.entity.ResponseBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/1/2.
 */

public class SearchActivity extends BaseActivity {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_search)
    RecyclerView rvSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_history)
    RecyclerView rvHistory;
    @BindView(R.id.rl_history)
    RelativeLayout rlHistory;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_del_history)
    TextView tvDelHistory;
    @BindView(R.id.rl_del)
    RelativeLayout rlDel;
    private SearchAdapter mSearchAdapter;
    private SearchHistoryAdapter mSearchHistoryAdapter;
    String strId[];
    private List<SharesBean.SharesInfo> sharesInfos = new ArrayList<>();
    private String searchText;
    int nearHistory = 5;//显示记录条数
    private List<String> mList = new ArrayList<>();
    private int mCurrentPage;
    private int currentSize;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        etSearch.addTextChangedListener(textWatcher);
        mCurrentPage = 1;
        refreshLayout.setVisibility(View.GONE);
        rvSearch.setLayoutManager(new LinearLayoutManager(getContext()));
        rvSearch.setNestedScrollingEnabled(false);
        mSearchAdapter = new SearchAdapter(null, getContext());
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableRefresh(true);
        rvSearch.setAdapter(mSearchAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    mCurrentPage = 1;
                    getCollectSharesId();
                }
            }
        });

        mSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SharesBean.SharesInfo sharesInfo = sharesInfos.get(position);
                Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                intent.putExtra("sharesInfo", sharesInfo);
                startActivity(intent);
            }
        });
        mSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SharesBean.SharesInfo sharesInfo = sharesInfos.get(position);
                if (view.getId() == R.id.ll_collect) {
                    if (PreferenceUtils.getLoginStatus()) {
                        if (Util.useList(strId, sharesInfo.getId())) {
                            cancelCollectShares(sharesInfo.getId());
                        } else {
                            collectSharesInfo(sharesInfo.getId());
                        }
                    } else {
                        toLogin();
                    }

                } else {
                    Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                    startActivity(intent);
                }
            }
        });

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                                       int oldScrollY) {
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    onLoadMoreRequested();
                }
            }
        });

        setHistory();
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                rlDel.setVisibility(View.INVISIBLE);
            } else {
                rlDel.setVisibility(View.VISIBLE);
            }
        }
    };

    private void setHistory() {
        SharedPreferences sp = getSharedPreferences("auto_text", MODE_PRIVATE);
        String history = sp.getString("history", "");
        if (!"".equals(history)) {
            tvDelHistory.setVisibility(View.VISIBLE);
            String[] hisArrays = history.split(",");
            if (hisArrays.length > 0) {
                //布局可以自己创建,用android自带的也行
                for (int i = 0; i < hisArrays.length; i++) {
                    mList.add(hisArrays[i].toString());
                }
            }
        } else {
            tvDelHistory.setVisibility(View.GONE);
        }
        rvHistory.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvHistory.setNestedScrollingEnabled(false);
        mSearchHistoryAdapter = new SearchHistoryAdapter(mList, getContext());
        rvHistory.setAdapter(mSearchHistoryAdapter);

        mSearchHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mList != null) {
                    searchText = mList.get(position);
                    etSearch.setText(searchText);
                    etSearch.setSelection(etSearch.getText().toString().length());
                    getCollectSharesId();
                    rlHistory.setVisibility(View.GONE);
                }
            }
        });
    }

    public void getCollectSharesId() {
        NetWork.getSharesApi().getCollectShareId()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CollectShareId>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        collectSharesId(new String[0]);
                    }

                    @Override
                    public void onNext(CollectShareId collectShareId) {
                        if (collectShareId.getCode().equals(Constant.SUCCESS_CODE)) {
                            int collectShareIds[] = collectShareId.getCollectShareIds();
                            String str[] = new String[collectShareIds.length];
                            for (int i = 0; i < collectShareIds.length; i++) {
                                str[i] = collectShareIds[i] + "";
                            }
                            collectSharesId(str);
                        } else {
                            ToastUitl.show(collectShareId.getMsg(), 200);
                        }

                    }
                });
    }

    public void getBondInfo(final int page) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("pageNum", page);
        hashMap.put("pageSize", 50);
        hashMap.put("search", searchText);
        NetWork.getSharesApi().bondInfo(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SharesBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.show(e.getMessage(), 200);
                        finishRefresh();
                    }

                    @Override
                    public void onNext(SharesBean collectSharesBean) {
                        finishRefresh();
                        if (collectSharesBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            rlHistory.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                            if (collectSharesBean.getShares() != null) {
                                if (page == 1) {
                                    setSharesData(collectSharesBean.getShares(), false);
                                } else {
                                    setSharesData(collectSharesBean.getShares(), true);
                                }
                            } else {
                                mSearchAdapter.setNewData(null);
                            }
                        } else {
                            ToastUitl.show(collectSharesBean.getMsg(), 200);
                        }
                    }
                });
    }

    public void collectSharesInfo(String sharesId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sharesId", sharesId);
        NetWork.getSharesApi().collectSharesInfo(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("收藏成功", 200);
                            refresh();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }
                    }
                });
    }

    public void cancelCollectShares(String sharesId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sharesId", sharesId);
        NetWork.getSharesApi().cancelCollectShares(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("取消收藏", 200);
                            refresh();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }
                    }
                });
    }

    public void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
    }

    public void refresh() {
        getCollectSharesId();
    }

    public void collectSharesId(String[] str) {
        strId = str;
        getBondInfo(mCurrentPage);
    }

    public void setSharesData(List<SharesBean.SharesInfo> sharesInfoList, boolean isLoadOver) {
        currentSize = sharesInfoList.size();
        mSearchAdapter.setCollectShareId(strId);
        if (isLoadOver) {
            sharesInfos.addAll(sharesInfoList);
            mSearchAdapter.addData(sharesInfoList);
        } else {
            sharesInfos = sharesInfoList;
            mSearchAdapter.setNewData(sharesInfos);
        }


    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();
    }

    /**
     * 把内容保存到sp中
     */
    private void saveHistory() {
        String text = etSearch.getText().toString();
        SharedPreferences sp = getSharedPreferences("auto_text", MODE_PRIVATE);
        String history = sp.getString("history", "");
        //先判断是否已经存过一样的文字
        if (!TextUtils.isEmpty(text) && !history.contains(text + ",")) {
            StringBuilder sb = new StringBuilder(history);
            sb.insert(0, text + ",");//插入到第一个,代表最新
            sp.edit().putString("history", sb.toString()).apply();
//            Toast.makeText(getContext(), "存好了", Toast.LENGTH_SHORT).show();
        } else {
//            Toast.makeText(getContext(), "存过了", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick({R.id.ll_search, R.id.tv_del_history, R.id.ll_back,R.id.rl_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
                searchText = etSearch.getText().toString();
                if ("".equals(searchText)) {
                    ToastUitl.show("请输入股票代码", 200);
                } else {
                    saveHistory();
                    getCollectSharesId();
                }
                break;
            case R.id.tv_del_history:
                SharedPreferences sp = getSharedPreferences("auto_text", MODE_PRIVATE);
                sp.edit().putString("history", "").apply();
                tvDelHistory.setVisibility(View.GONE);
                mList.clear();
                mSearchHistoryAdapter.setNewData(mList);
                break;
            case R.id.rl_del:
                etSearch.setText("");
                rlDel.setVisibility(View.GONE);
                break;
            case R.id.ll_back:
                finish();
                break;
        }
    }

    public void onLoadMoreRequested() {
        if (currentSize >= 50) {
            mCurrentPage++;
            getBondInfo(mCurrentPage);
        }
    }
}
